package com.hcss.sys.menu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hcss.common.base.BaseClass;
import com.hcss.common.constant.ConfigConstants;
import com.hcss.qywechat.user.model.WQyUser;
import com.hcss.sys.menu.constant.MenuConstants;
import com.hcss.sys.menu.model.HcSysMenu;
import com.hcss.sys.menu.model.par.HcSysMenuPar;
import com.hcss.sys.menu.model.vo.HcSysMenuVO;
import com.hcss.sys.menu.service.MenuService;
import com.hcss.sys.role.model.HcSysRole;
import com.hcss.sys.role.model.vo.HcSysRolemenuVO;
import com.hcss.sys.role.service.RoleService;
import com.hcss.update.model.UpdateSchema;
import com.hcss.util.AjaxResult;
import com.hcss.util.BeanCopyUtil;
import com.hcss.util.EmptyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;
import java.util.List;

/**
 * @描述: Menu功能模块
 * @作者: fangtao
 * @创建日期: 2019-01-07 16:56:48
 */
@Slf4j
@RestController
@RequestMapping("menu")
public class MenuController {

	@Autowired
    private MenuService menuService;

	@Autowired
	private RoleService roleService;

    @Autowired
    private ConfigConstants configConstants;


	/**
	 * 更新插入的schema，用于鉴定数据的安全性
	 */
    static UpdateSchema updateSchema = new UpdateSchema(HcSysMenu.class, new String[]{"name", "fatherid", "showLevel"},
			new String[]{"sort", "isDelete"});

	/**
	 * Menu数据列表页面
     *
	 * @return
	 */
	@GetMapping("listPage")
	public ModelAndView listPage(){
		ModelAndView mav = new ModelAndView("/menu/menu-listPage");

		List<HcSysRole> allRole = roleService.selectAll();
		mav.addObject("allRole", JSON.toJSONString(allRole));
		return mav;
	}

	/**
	 * Menu数据接口
	 *
	 * @param fatherid 父节点id
	 * @return
	 */
	@PostMapping("/list")
	public AjaxResult list(String fatherid){
		if (EmptyUtil.isHaveEmpty(fatherid)) {
            return AjaxResult.getMissingParamResult();
        }
		Collection<HcSysMenu> list = menuService.getSysMenuByFatherid(fatherid);
		return new AjaxResult(list);
	}

	/**
	 * Menu新增或修改数据接口
	 *
	 * @param par 数据对象
	 * @return
	 */
	@PostMapping("/addOrUpdate")
	public AjaxResult addOrUpdate(HcSysMenuPar par){
		if (!UpdateSchema.checkAddOrUpdate(par, updateSchema)) {
            return AjaxResult.getMissingParamResult();
        }

		try {
			HcSysMenu model = BeanCopyUtil.copyConvey(par, HcSysMenu.class);
			model.setIsDelete(MenuConstants.IS_DELETE_NO);
			if (EmptyUtil.isHaveEmpty(model.getId())) {
				menuService.insertModel(model);
			} else {
				menuService.updateModel(model, updateSchema);
			}
			return new AjaxResult(model.getId());
		} catch (Exception e) {
			log.error("新增或更新操作出错，参数：" + par.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

    /**
	 * 根据id进行删除
	 * @param id
	 * @return
	 */
	@PostMapping("/delete")
	public AjaxResult deleteByIds(String id){
		if (EmptyUtil.isHaveEmpty(id)) {
            return AjaxResult.getMissingParamResult();
        }
		try {
			menuService.deleteById(id);
			return new AjaxResult();
		} catch (Exception e) {
            log.error("删除出错，参数：[{}]",id, e);
            return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 批量修改菜单 移动位置
	 * @param menuList
	 * @return
	 */
	@PostMapping("batchUpdate")
	public AjaxResult batchUpdate(@RequestBody List<HcSysMenu> menuList) {
		if (CollectionUtils.isNotEmpty(menuList)) {
			for (HcSysMenu model : menuList) {
				menuService.updateModelSelective(model);
			}
		}
		return new AjaxResult();
	}

	/**
	 * 根据角色id获取关联的菜单集合
	 * @param rolemenuVO
	 * @return
	 */
	@PostMapping("/getByRole")
	public AjaxResult getByRole(HcSysRolemenuVO rolemenuVO) {
		if (EmptyUtil.isHaveEmpty(rolemenuVO.getRoleid())) {
            return AjaxResult.getMissingParamResult();
        }

		List<HcSysMenu> selectedMenu = menuService.selectByRole(rolemenuVO);
		return new AjaxResult(selectedMenu);
	}

	/**
	 * 获取登录用户拥有菜单权限
	 * @return
	 */
	@GetMapping("/loginmenu")
	public AjaxResult getLoginUserMenu() {
		WQyUser user = (WQyUser) SecurityUtils.getSubject().getPrincipal();
		List<HcSysMenuVO> menuList = menuService.selectByUserid(user.getUserid());

        JSONObject menu = new JSONObject();
        menu.put("menuList", HcSysMenuVO.build(menuList));
		return new AjaxResult(menu);
	}

    /**
     * 校验当前登录用户是否有参数url的访问权限
     * @param key 要校验的链接
     * @return
     */
	@GetMapping("access")
	public AjaxResult access(String key) {
	    if (StringUtils.isBlank(key)) {
            return AjaxResult.getErrorResult("校验链接不能为空");
        }
        AjaxResult ajaxResult = new AjaxResult();
        List<String> urls = menuService.selectUserMobileUrl(BaseClass.getSessionUserid());
        if (CollectionUtils.isEmpty(urls)) {
            ajaxResult.put("access", false);
        } else {
            ajaxResult.put("access", urls.contains(key));
        }
	    return ajaxResult;
    }
}